﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using TheGameClient.Processes;
using TheGameClient.Webservices;
using Waaahsabi.Controls.FileSystem;

namespace TheGameClient
{
	public partial class FeatureFileSystemControl : IFileManager, ISystemFeature
	{
		private ObservableCollection<SystemFileItem> _fileItems;

		public FeatureFileSystemControl()
		{
			InitializeComponent();
			ProcessId = Guid.NewGuid();
			_fileItems = new ObservableCollection<SystemFileItem>();
			itmFileItems.ItemsSource = _fileItems;
			HorizontalAlignment = HorizontalAlignment.Stretch;
			VerticalAlignment = VerticalAlignment.Stretch;
		}

		public ObservableCollection<SystemFileItem> FileItems
		{
			get
			{
				if (_fileItems == null)
					_fileItems = new ObservableCollection<SystemFileItem>();
				return _fileItems;
			}
		}

		#region IFileManager Members

		public ulong DirectoryId { get; set; }

		public event EventHandler OnRefreshRequested;

		public void RefreshContent()
		{
			TheGameServiceClient client = App.Client;
			client.GetSystemRootCompleted += ClientGetSystemRootCompleted;
			client.GetSystemRootAsync(App.InternalSessionId, SystemId);
		}

		#endregion

		#region ISystemFeature Members

		public ulong InterfaceId
		{
			get { return new Guid("{4B8BE4AF-D6D8-416c-B98E-7330786F1530}").ToLong(); }
		}

		public Guid ProcessId { get; private set; }

		public string ProcessName
		{
			get { return "File system"; }
		}

		public InterfaceCategory Category
		{
			get { return InterfaceCategory.SystemFeature; }
		}

		public ulong SystemId { get; private set; }

		public void Load(ulong systemId)
		{
			SystemId = systemId;
			RefreshContent();
		}

		#endregion

		private void ClientGetSystemRootCompleted(object sender, GetSystemRootCompletedEventArgs e)
		{
			App.Client.GetSystemRootCompleted -= ClientGetSystemRootCompleted;
			if (e.Error != null)
			{
				App.ServerError();
				return;
			}
			if (e.Result != null)
			{
				_fileItems.Clear();
				foreach (SystemFile f in e.Result)
				{
					if (DirectoryId == 0)
						DirectoryId = f.ParentId;

					SystemFileItem fi = new SystemFileItem
					{
						FileName = f.Name,
						FileId = f.Id,
						FileSize = f.DisplaySize.ToString(),
						FileType = f.Type.ToString()
					};
					_fileItems.Add(fi);
				}
			}
		}
	}

	public class FeatureFileSystemUiFactory : UiFactoryBase
	{
		public override InterfaceCategory UiCategory
		{
			get { return InterfaceCategory.SystemFeature; }
		}

		public override IProcess CreateProgram()
		{
			return new FeatureFileSystemControl();
		}
	}
}